import Vue from "vue";
import VueRouter from "vue-router";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    redirect: "/home",
  },
  {
    path: "/home",
    component: () => import("@/layout/index.vue"),
    meta: { title: "布局" },
    name: "home",
    children: [
      {
        //目前是单纯的页面,没有左侧导航对应,只是写着玩,具体实现可以用动态组件components实现
        path: "router",
        component: () => import("@/views/routerView/index.vue"),
        children: [
          {
            path: "a",
            components: {
              //同一个路由切换内容的写法,配合router-view的name属性使用
              default: () => import("@/views/routerView/components/page1.vue"),
              page2: () => import("@/views/routerView/components/page2.vue"),
            },
          },
        ],
      },
    ],
  },

  {
    path: "/login",
    component: () => import("@/views/login"),
    meta: {
      title: "登录",
    },
  },
  {
    path: "/register",
    component: () => import("@/views/register"),
    meta: {
      title: "注册",
    },
  },
];
//404页面要在所有动态路由注册之后进行注册,要不然直接访问还没动态添加的路由的时候,就会直接进入404页面
export const errObj = {
  path: "*",
  component: () => import("@/views/404.vue"),
  name: "404",
  meta: {
    title: "404页面",
  },
};

//解决一些跳转bug
//重写push的catch方法
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location) {
  return originalPush.call(this, location).catch((err) => {});
};
VueRouter.prototype.replace = function (location) {
  return originalPush.call(this, location).catch((err) => {});
};

const createRouter = () => {
  
  return new VueRouter({
    mode: "history",
    routes: routes,
    // scrollBehavior(to, from, savedPosition) {
    //   if (savedPosition) {
    //     console.log(savedPosition, 1111);
    //     return savedPosition;
    //   } else {
    //     console.log(111);
    //     return { x: 0, y: 0  , behavior: 'smooth'};
    //   }
    //   // return 期望滚动到哪个的位置
    // },
    //跳转的时候可以用,但是是整个页面的滚动,要是在layout里面的滚动条就见不到了
  });
};
const router = createRouter();
//重置路由, 如果路由不进行重置的话,退出登录后下一个用户还可以进入上一个人的权限页面,比如管理员登录退出后,普通用户登录,n那么用户还可以直接进入管理员的页面
export function resetRouter() {
  const newRouter = createRouter();
  router.matcher = newRouter.matcher;
}
export default router;
